<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614>　
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\facade\Config;
use think\Db;


class Auth {
    //默认配置
    protected $config = array(
        'auth_on'           => true,                      // 认证开关
        'auth_type'         => 1,                         // 认证方式，1为实时认证；2为登录认证。
        'auth_group'        => 'auth_group',        // 用户组数据表名
        'auth_group_access' => 'auth_group_access', // 用户-用户组关系表
        'auth_rule'         => 'auth_rule',         // 权限规则表
        'auth_user'         => 'admin_list'             // 用户信息表
    );

    public function __construct() {
        if (Config::get('auth_config')) {
            $this->config = array_merge($this->config, Config::get('auth_config')); //可设置配置项 auth_config, 此配置项为数组。
        }
    }

    public function check($name, $uid, $type = 1) {
        if (!$this->config['auth_on']) {
            return true;
        }
        $authList = $this->getAuthList($uid, $type); //获取用户需要验证的所有有效规则列表
        if (is_string($name)) {
            $name = strtolower($name);
            $name = [$name];
        }
        $list = []; //保存验证通过的规则名
        foreach ($authList as $auth) {
            if (in_array($auth,$name)) {
                $list[] = $auth;
            }
        }
        if (!empty($list)) {
            return true;
        }
        return false;
    }


    public function getGroups($uid) {
        static $groups = [];
        if (isset($groups[$uid])) {
            return $groups[$uid];
        }
        $user_groups = Db::name('auth_group')->where('id',Db::name('auth_group_access')->where('uid',$uid)->value('group_id'))->select();
        $groups[$uid] = $user_groups ? $user_groups : [];
        return $groups[$uid];
    }


    protected function getAuthList($uid, $type) {
        //读取用户所属用户组
        $groups = $this->getGroups($uid);
        $ids = [];
        foreach ($groups as $g){
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        //读取用户组所有权限规则
        $rules = Db::name('auth_rule')
            ->where('id','in',$ids)
            ->where('type',$type)
            ->where('status',1)
            ->field('condition,name')->select();
        //循环规则，判断结果。
        $authList = [];   //
        foreach ($rules as $rule) {
            $authList[] = strtolower($rule['name']); //只要存在就记录
        }
        return array_unique($authList);
    }
}